use semver::Version;
use std::path::{Path, PathBuf};
use crate::{config::Config, repo::ModelManifest};

pub struct VersionManager;

impl VersionManager {
    pub fn resolve_version(model: &str, version: Option<&str>) -> Result<String, VersionError> {
        let manifest = crate::repo::fetch_model_manifest(model)?;
        
        match version {
            Some(v) => manifest.versions
                .iter()
                .find(|mv| mv.version == v)
                .map(|mv| mv.version.clone())
                .ok_or(VersionError::VersionNotFound),
            None => manifest.versions
                .iter()
                .find(|mv| mv.recommended)
                .map(|mv| mv.version.clone())
                .ok_or(VersionError::NoRecommendedVersion)
        }
    }

    pub fn get_model_path(model: &str, version: &str) -> PathBuf {
        let config = Config::load().unwrap();
        config.models_dir
            .join(model)
            .join(version)
    }
}

#[derive(Debug, thiserror::Error)]
pub enum VersionError {
    #[error("Version not found")]
    VersionNotFound,
    #[error("No recommended version available")]
    NoRecommendedVersion,
    #[error("Repository error: {0}")]
    Repo(#[from] crate::repo::RepoError),
}